<template>
  <el-autocomplete
    v-model="p_value"
    class="inline-input"
    :trigger-on-focus="triggerOnFocus"
    :fetch-suggestions="queryUserSearch"
    :placeholder="placeholder"
  >
    <i
      v-show="p_value.length > 0"
      slot="suffix"
      class="el-icon-circle-close el-input__icon"
      @click="handleIconClick"
    ></i>
  </el-autocomplete>
</template>

<script>
import { getUserListByUserName } from '@/api/user'
export default {
  name: 'User',
  props: {
    value: {
      type: String,
      default: ''
    },
    triggerOnFocus: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      userList: [],
      p_value: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        this.p_value = val
      },
      immediate: true
    },
    p_value: {
      handler(val) {
        this.$emit('change', val)
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    handleIconClick() {
      this.p_value = ''
    },
    getUserList() {
      getUserListByUserName({ userName: '' }).then((res) => {
        this.userList = res.data
      })
    },
    queryUserSearch(queryString, cb) {
      var restaurants = this.userList
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    }
  }
}
</script>

<style scoped>
.inline-input .el-icon-circle-close {
  display: none;
}
.inline-input:hover .el-icon-circle-close {
  display: block;
}
</style>
